package com.xiguthings.xiniu.iot.trigger.worker.regist;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.ExecutionException;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import com.xiguthongs.xiniu.iot.register.ConnectionConfiguration;
import com.xiguthongs.xiniu.iot.register.RegistTools;
import com.xiguthongs.xiniu.iot.register.Register;

@Component
public class ServiceRegistry {
	private static final Logger LOGGER = LoggerFactory.getLogger(ServiceRegistry.class);
	@Value("${etcd_endpoints}")
	private String etcdEndpoints;

	@Value("${modleName}")
	private String modleName;

	@Value("${is_need_regist}")
	private Boolean isNeedRegist;

	@PostConstruct
	private void run() {
		if (isNeedRegist == null || isNeedRegist == false) {
			return;
		}
		// 创建连接注册中心的配置
		ConnectionConfiguration connectionConfiguration = RegistTools.addEtcdPoint(etcdEndpoints, null);
		// 关于版本的文件
		InputStream inputStream = null;
		Properties properties = new Properties();

		ClassPathResource classPathResource = new ClassPathResource("banner.txt");
		try {
			inputStream = classPathResource.getInputStream();
			properties.load(inputStream);
			RegistTools.registByProperties(connectionConfiguration, Register.MODULE_TYPE_WORKER, modleName, properties);
		} catch (IOException e1) {
			LOGGER.error("注册失败读取项目的版本失败！", e1);
		} catch (ExecutionException e) {
			LOGGER.error("服务注册失败:{}", e);
		} catch (Exception e) {
			LOGGER.error("", e);
		} finally {
			try {
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException e) {
				LOGGER.error("", e);
			}

		}

	}

}
